package com.example.common.security.service;

import cn.hutool.core.lang.UUID;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.constants.JWTConstants;
import com.example.common.core.model.LoginUser;
import com.example.common.redis.service.RedisService;
import com.example.common.core.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/3/18
 */
@Slf4j
@Service
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(Long userId, String secret, Integer identity,
    String nickName,String headImage) {
        Map<String, Object> claims = new HashMap<>();
        //使用UUID来作为用户的唯一标识
        String userKey = UUID.fastUUID().toString();
        claims.put(JWTConstants.LOGIN_USER_ID, userId);
        claims.put(JWTConstants.LOGIN_USER_KEY, userKey);
        //创建token
        String token = JWTUtils.createToken(claims, secret);
        //拼接key：前缀 + 用户唯一标识
        String key = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        //把用户唯一标识和用户信息映射存储Redis
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(key, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }

    /**
     * 延长token过期时间
     *
     */
    public void extendToken(Claims claims){
        String userKey = getUserKey(claims);
        if(userKey == null){
            return;
        }
        String tokenKey = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        //先获取剩余过期时间，如果小于阈值就延长
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if(expire != null && expire < CacheConstants.REFRESH_TIME){
            redisService.expire(tokenKey,CacheConstants.EXP,TimeUnit.MINUTES);
        }
    }

    public LoginUser getLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
    }


    public boolean deleteLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.valueOf(JWTUtils.getUserId(claims));  //获取jwt中的key
    }

    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        return JWTUtils.getUserKey(claims);  //获取jwt中的key
    }

    private String getUserKey(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JWTUtils.getUserKey(claims);  //获取jwt中的key
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JWTUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}, 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}, 出现异常", token, e);
            return null;
        }
        return claims;
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }

    private String getTokenKey(String userKey) {
        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }
}
